import 'dart:io';
import 'package:flutter/services.dart';
///@description: 文件工具
class FileUtils {
  ///递归创建文件夹，如果是应用外部路径需要获取存储权限
  ///[path] 文件夹路径，例如/lib/temp/
  static Future<Directory> createDir(String path) {
    Directory directory = Directory(path);
    return directory.create(recursive: true);
  }

  ///递归创建文件
  ///[path] 文件所在目录，自动创建目录，例如：/lib/temp/
  ///[filePath] 文件名，例如：test.txt
  static Future<File> createFile(String path, String fileName) async {
    Directory dir = await createDir(path);
    return File("${dir.path}/$fileName").create(recursive: true);
  }

  ///write to app path
  static Future<File> writeToFile(ByteData data, String path) async {
    final buffer = data.buffer;
    File file = await File(path).writeAsBytes(
        buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
    return file;
  }

  /// 判断文件是否存在
  static Future<bool> isFileExists(String filePath) async {
    return File(filePath).exists();
  }

  /// 删除文件
  static Future<bool> deleteFile(String path) async {
    File file = File(path);
    if (await file.exists()) {
      await file.delete(recursive: true);
    }
    return true;
  }
}
